/**
 * http请求拦截器
 */
import Fly from 'flyio'
import config from './config'

const ajaxUrl =
    process.env.NODE_ENV === 'development'
        ? config.Host.development
        : process.env.NODE_ENV === 'production'
            ? config.Host.production
            : config.Host.test

let fly = new Fly()
let loginFly = new Fly()
let loadingTimer = [] // loading的定时器
// 定义公共headers
const headers = {
    // 'Content-Type': 'application/x-www-form-urlencoded '
}
fly.config = Object.assign(fly.config, {
    headers: headers,
    baseURL: ajaxUrl,
    timeout: 25000,
    withCredentials: true
})
loginFly.config = fly.config
// session失效后本地重新登录
const login = () => {
    return new Promise((resolve, reject) => {
        wx.login({
            success: res => {
                let loginParams = {
                }
                let openId = wx.getStorageSync('openid')
                if (!openId) {
                    loginFly.post(`/User/loginByOpenId?openId=${openId}`, loginParams).then(d => {
                        if (d.data !== 'undefined') {
                            // 更新session
                            wx.setStorageSync('token', d.data)
                        }
                        resolve()
                    }).catch(error => {
                        console.log(error)
                        reject(res.data)
                    })
                }
            },
            fail: res => {
                console.error(res.errMsg)
            },
            complete: res => { }
        })
    })
}
// 请求拦截器
fly.interceptors.request.use(request => {
    // 开启loading
    clearTimeout(loadingTimer) // 多个接口时需要清除上一个loading
    loadingTimer = setTimeout(() => {
        config.loading.loadingShow()
    }, config.loading.limitTime)
    if (wx.getStorageSync('token')) {
        request.headers['Authorization'] = wx.getStorageSync('token')
    }
    return request
})
// 响应拦截器
fly.interceptors.response.use(
    response => {
        clearTimeout(loadingTimer)
        config.loading.loadingHide()
        // session已经失效，需要重新登录小程序
        if (response.data.errCode === 100009) {
            // log('session失效，根据之前存储在本地的用户信息重新请求session...')
            // 锁定响应拦截器
            fly.lock()
            return login().then(() => {
                fly.unlock()
                // log(`重新请求：path:${response.request.url}，baseURL:${response.request.baseURL}`)
                return fly.request(response.request)
            }).catch(err => {
                console.log(err)
            })
        } else {
            if (response.data.state !== 'success') {
                wx.showToast({
                    title: response.data.message,
                    icon: 'none',
                    mask: true,
                    duration: 1000
                })
            }
            return response.data
        }
    },
    err => {
        console.log('error-interceptor', err)
        clearTimeout(loadingTimer) // 请求异常则直接清除loading计时器
        if (err.status) {
            config.resError.tipShow(err)
        }
    }
)
export default fly
